#pragma once
#include "mq_worker.hpp"
#include "muduo/net/TcpClient.h"
#include "muduo/protoc/codec.h"
#include "muduo/protoc/dispatcher.h"

#include "muduo/base/Logging.h"
#include "muduo/net/TcpClient.h"

#include "muduo/base/CountDownLatch.h"
#include "muduo/net/Callbacks.h"
#include "muduo/net/EventLoopThread.h"

#include <memory>
#include <unistd.h>
#include "mq_channal.hpp"
namespace mq_zxws {
    class Connection {
    public:
        using ptr = std::shared_ptr<Connection>;
        Connection(const std::string &ip, int port, const AsyncWorker::ptr & worker)
            :_latch(1)
            ,_client(worker->loopthread.startLoop(),muduo::net::InetAddress(ip, port), "Client")
            ,_dispatcher(std::bind(&Connection::onUnknownMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
            ,_codec(std::make_shared<ProtobufCodec>(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))) 
            ,_worker(worker)
            ,_channal_manager(std::make_shared<ChannalManager>())
        {
            _dispatcher.registerMessageCallback<basicCommonResponce>(std::bind(&Connection::basicResponce, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
            _dispatcher.registerMessageCallback<basicConsumerResponce>(std::bind(&Connection::consumerResponce, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
            _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, _codec.get(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
            _client.setConnectionCallback(std::bind(&Connection::onConnetion, this, std::placeholders::_1));
            
            _client.connect();
            _latch.wait();
        }

        Channal::ptr openChannal(){
            Channal::ptr channal = _channal_manager->create(_conn, _codec);
            if(!channal->openChannal()){
                DLOG("打开信道失败");
                return Channal::ptr();
            }
            return channal;
        }
        void closeChannal(const Channal::ptr & channal){
            channal->closeChannal();
            _channal_manager->remove(channal->cid());
        }

    private:
        void onConnetion(const muduo::net::TcpConnectionPtr &conn) {
            if (conn->connected()) {
                _conn = conn;
                _latch.countDown();
            } else {
                _conn.reset();
            }
        }
        void basicResponce(const muduo::net::TcpConnectionPtr &conn, const basicCommonResponcePtr &message, muduo::Timestamp) {
            // 1、找到信道
            Channal::ptr channal = _channal_manager->getChannal(message->cid());
            DLOG("cid: %s rid: %s ok: %d", message->cid().c_str(), message->rid().c_str(), message->ok());
            if(channal.get() == nullptr){
                DLOG("未找到信道信息");
                return;
            }
            // 2、得到响应对象，添加到信道的基础响应hashmap中
            channal->putBasicResponce(message);
        }
        void consumerResponce(const muduo::net::TcpConnectionPtr &conn, const basicConsumerResponcePtr &message, muduo::Timestamp) {
            // 1、找到信道
            Channal::ptr channal = _channal_manager->getChannal(message->cid());
            DLOG("cid: %s", message->cid().c_str());
            if(channal.get() == nullptr){
                DLOG("未找到信道信息 %s", message->cid().c_str());
                return;
            }
            // 2、封装异步任务，抛入线程池
            _worker->pool.push([channal, message](){
                channal->consumer(message);
            });
        }
        void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn, const MessagePtr &message, muduo::Timestamp) {
            LOG_INFO << "onUnkownMessage: " << message->GetTypeName();
            conn->shutdown();
        }
    private:
        muduo::CountDownLatch _latch; // 实现同步
        muduo::net::TcpConnectionPtr _conn; // 客户端对应的连接
        muduo::net::TcpClient _client; // 客户端
        ProtobufDispatcher _dispatcher; // 请求分发器
        ProtobufCodecPtr _codec; // 协议处理器

        AsyncWorker::ptr _worker;
        ChannalManager::ptr _channal_manager;
    };
} // namespace mq_zxws